package com.jinyang.jetpackdemo.paging3

import androidx.lifecycle.viewModelScope
import androidx.paging.*
import androidx.room.Entity
import coil.map.Mapper
import com.jinyang.jetpackdemo.util.LjyLogUtil
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/8/16
 *
 */
object Repository {
    const val PAGE_SIZE = 5
    private val gitHubService = ApiService.create()
    private val db = AppDatabase.instance
    private val pagingConfig = PagingConfig(
        // 每页显示的数据的大小
        pageSize = PAGE_SIZE,
        // 开启占位符
        enablePlaceholders = true,
        // 预刷新的距离，距离最后一个 item 多远时加载数据
        // 默认为 pageSize
        prefetchDistance = PAGE_SIZE,
        // 初始化加载数量，默认为 pageSize * 3
        initialLoadSize = PAGE_SIZE
    )

    fun getPagingData(): Flow<PagingData<Repo>> {
        // PagingConfig的一个参数prefetchDistance，用于表示距离底部多少条数据开始预加载，
        // 设置0则表示滑到底部才加载。默认值为分页大小。
        // 若要让用户对加载无感，适当增加预取阈值即可。 比如调整到分页大小的5倍
        return Pager(config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = { RepoPagingSource(gitHubService) }).flow
    }

    @OptIn(ExperimentalPagingApi::class)
    fun getPagingData2(): Flow<PagingData<Repo>> {
        return Pager(
            config = pagingConfig,
            remoteMediator = RepoMediator(gitHubService, db)
        ) {
            db.repoDao().get()
        }.flow.map { pagingData ->
            pagingData.map { RepoEntity2RepoMapper().map(it) }
        }
    }
}

class RepoEntity2RepoMapper : Mapper<RepoEntity, Repo> {
    override fun map(input: RepoEntity): Repo = Repo(
        id = input.id,
        name = input.name,
        description = input.description,
        starCount = input.starCount
    )
}